package top.zt9.controller;

import com.qf.util.MD5Utils;
import com.qf.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.zt9.form.SmsInterfaceForm;
import top.zt9.service.SmsInterfaceService;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ztf
 * @Date 21:54 2021/11/21
 **/
@RestController
@RequestMapping("/sms")
@Slf4j
public class smsInterfaceController {

    /**
     * 获取Gitee配置文件中nginx代理的ip地址, 请求头信息
     */
    @Value("${ip-header}")
    private List<String> ipHeaders;

    @Autowired
    private SmsInterfaceService smsInterfaceService;

    /**
     * 接收用户请求, 返回响应编码
     * 请服务方url地址：http://ip:port/smsInterface,客户方将下行数据发送到该url
     *
     * @return
     */
    @PostMapping("/smsInterface")
    public Map smsInterface(SmsInterfaceForm smsInterfaceForm, HttpServletRequest req) {
        //获取用户请求时携带的ip地址
        String realIpAddress = this.getRealIpAddress(req);
        //将ip地址封装到form对象
        smsInterfaceForm.setIp(realIpAddress);
        //对参数进行非空校验
        Map resultMap = this.checkNotNull(smsInterfaceForm);

        if (resultMap.size()!=0) {
            log.info("[接口模块 - 接口客户请求] 参数非空校验失败! resultMap = {}, interfaceForm= {}", resultMap, smsInterfaceForm);
            return resultMap;
        }
        //对pwd加密
//        smsInterfaceForm.setPwd(DigestUtils.md5DigestAsHex(smsInterfaceForm.getPwd().getBytes(StandardCharsets.UTF_8)));
        smsInterfaceForm.setPwd(MD5Utils.generateMd5(smsInterfaceForm.getPwd()));
        //调用service进行处理
        resultMap = smsInterfaceService.checkInterfaceForm(smsInterfaceForm);

        return resultMap;
    }

    /**
     * 校验从请求头获取的参数是否正确,获取ip
     *
     * @param req
     * @return
     */
    private String getRealIpAddress(HttpServletRequest req) {
        for (String ipHeader : ipHeaders) {
            //判断ip是否为空
            if (!StringUtils.isEmpty(ipHeader)) {
                //获取真实ip
                String ip = req.getHeader(ipHeader);
                //判断是否真的拿到ip
                if (!StringUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
                    return ip;
                }
            }
        }
        //5. 循环结束,没有拿到真实的ip地址,通过传统的方式获取ip
        return req.getRemoteAddr();
    }

    /**
     * 对参数进行非空校验
     *
     * @param smsInterfaceForm
     * @return
     */
    private Map checkNotNull(SmsInterfaceForm smsInterfaceForm) {
        Map<String, String> resultMap = new HashMap();
        if (StringUtils.isEmpty(smsInterfaceForm.getClientID())) {
            resultMap.put("code", "101");
            resultMap.put("msg", "认证错：clientId错误");
            return resultMap;
        }
        if (StringUtils.isEmpty(smsInterfaceForm.getPwd())) {
            resultMap.put("code", "102");
            resultMap.put("msg", "密码错误");
            return resultMap;
        }
        if (StringUtils.isEmpty(smsInterfaceForm.getIp())) {
            resultMap.put("code", "103");
            resultMap.put("msg", "IP校验错误");
            return resultMap;
        }
        if (StringUtils.isEmpty(smsInterfaceForm.getContent()) || smsInterfaceForm.getContent().length() > 500) {
            resultMap.put("code", "104");
            resultMap.put("msg", "消息长度错，为空或超长（目前定为500个字）");
            return resultMap;
        }
        if (StringUtils.isEmpty(smsInterfaceForm.getMobile())) {
            resultMap.put("code", "105");
            resultMap.put("msg", "手机号错误");
            return resultMap;
        }
        if (StringUtils.isEmpty(smsInterfaceForm.getSrcID())) {
            resultMap.put("code", "106");
            resultMap.put("msg", "下行编号（srcID）错误");
            return resultMap;
        }
        return resultMap;
    }
}
